<template>

  <el-card class="box-card">
    <div class="table-header">
      <div>
        <el-input
                style="width: 200px"
                v-model="urlParams.search"
                placeholder="请输入账号"
                clearable
                @clear="onSearch"
                @keyup.enter="onSearch"
        ></el-input>
        &nbsp
        <!--状态-->
        <el-select v-model="urlParams.status" style="width: 170px" class="m-2" clearable placeholder="请选择状态" @clear="onSearch">
          <el-option value="1" label="成功" @click="onSearch"></el-option>
          <el-option value="2" label="失败" @click="onSearch"></el-option>
        </el-select>
        <el-button type="primary" style="margin-left: 10px" @click="onSearch"><el-icon><search /></el-icon>查询</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="SearchReset"><el-icon><RefreshRight /></el-icon>重置</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="CleanLog"><el-icon><Delete /></el-icon>清空日志</el-button>
      </div>
       <!--清空日志对话框-->
       <el-dialog
          v-model="LogDialog"
          title="清空日志"
          width="30%"
    >
     <el-form :model="form" ref="formRef" :rules="formRules" label-width="100px">
        <el-form-item label="开始时间：" prop="start_time">
             <el-date-picker v-model="form.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="end_time">
            <el-date-picker v-model="form.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间">
            </el-date-picker>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="LogDialog = false">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>

  </el-dialog>


      <div>
        <!--展示列弹出框-->
        <el-popover placement="left" :width="100" v-model:visible="columnVisible" trigger="contextmenu">
          <template #reference>
            <el-button type="primary" @click="columnVisible = true"><el-icon><setting /></el-icon>&nbsp;展示列</el-button>
          </template>
              <el-checkbox v-model="showColumn.username">账号</el-checkbox>
              <el-checkbox v-model="showColumn.url">请求地址</el-checkbox>
              <el-checkbox v-model="showColumn.remote_ip">IP地址</el-checkbox>
              <el-checkbox v-model="showColumn.action">日志标题</el-checkbox>
              <el-checkbox v-model="showColumn.status">状态</el-checkbox>
              <el-checkbox v-model="showColumn.timestamp">操作时间</el-checkbox>
            <div style="text-align: right; margin: 0">
              <el-button size="small" type="Default" @click="columnVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="saveColumn">确认</el-button>
            </div>

        </el-popover>

      </div>
    </div>

    <!--数据表格-->
    <el-table
            :data="tableData"
            style="width: 100%"
            stripe
            :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }"
            v-loading="loading"
            @cell-dblclick="dbclick"
            :show-overflow-tooltip="true"
            height="390px"
            :row-style="{height: '0'}"
            :cell-style="{padding: '4.7px',textAlign: 'center'}"
    >
        <template #empty><el-empty description="暂无数据" /></template>
        <el-table-column prop="username" label="账号"  v-if="showColumn.username"/>
        <el-table-column prop="url" label="请求地址"  v-if="showColumn.url"/>
        <el-table-column prop="remote_ip" label="IP地址" v-if="showColumn.remote_ip"/>
        <el-table-column prop="action" label="日志标题" v-if="showColumn.action"/>
        <el-table-column prop="status" label="状态"  v-if="showColumn.status">
            <template #default="scope">
              <el-tag  type="success" v-if="scope.row.status == 1">成功</el-tag>
              <el-tag  type="danger" v-if="scope.row.status == 2">失败</el-tag>
            </template>
       </el-table-column>
        <el-table-column prop="timestamp" label="操作时间"  sortable v-if="showColumn.timestamp"/>

    </el-table>

    <!--分页-->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-card>


</template>

<script>

    export default {
        data() {
          return {
            LogDialog: false,
            form: {
                start_time: '',
                end_time: '',
            },
            loading: false,
            tableData: [],
            total: 0,  // 总数据条数
            pageSize: 10, // 默认每页的数据条数
            currentPage: 1,  // 默认开始页码
            urlParams: {  // URL查询参数
              page_num: 1,
              page_size: 10,
              search: '',
              status: '',
            },
            showColumn: {
              username: true,
              url: true,
              action: true,
              remote_ip: true,
              status: true,
              timestamp: true
            },
            columnVisible: false, // 展示与隐藏
            formRules: {
                   start_time: [
                      {required: true, message: '请选择时间', trigger: 'blur'},
                   ],
                   end_time: [
                      {required: true, message: '请选择时间', trigger: 'blur'},
                   ],
             },
          }
        },
        mounted() {
          this.getData();
          // 从浏览器本地存储获取历史展示列
          const columnSet = localStorage.getItem(this.$route.path + '-columnSet')
          // 如果本地有存储则使用
          if(columnSet) {
            this.showColumn = JSON.parse(columnSet)
          }
        },
        methods: {
          getData() {
            // 处理URL查询参数
            if(!this.urlParams.status) {
                  delete this.urlParams.status;
            }
            this.loading = true;
            this.$http.get('/config/operatelog/', {params: this.urlParams})
              .then(res => {
                // console.log(res.data);
                this.tableData = res.data.data;
                this.total = res.data.count;
                this.loading = false;
              })
              .catch(()=>{
                //由于分页第二页没有足够status=2数据来填充，导致查询报错404，只在分页为1的数据没有错误
              })
          },
           // 分页：监听【选择每页数量】的事件
          handleSizeChange(pageSize) {
              // console.log(pageSize)
              this.pageSize = pageSize; // 重新设置分页显示
              this.urlParams.page_size = pageSize;  // 将最新值设置到数据里，用于下面用新值重新获取数据
              this.getData()
          },
          // 分页：监听【点击页码】的事件
          handleCurrentChange(currentPage) {
              // console.log(currentPage)
              this.currentPage = currentPage; // 重新设置分页显示
              this.urlParams.page_num = currentPage;
              this.getData()
          },
          onSearch() {
            this.getData();
          },
          //重置查询的数据
          SearchReset() {
            this.urlParams.search = '';
            this.urlParams.status = '';
            this.getData();
          },
          saveColumn() {
            localStorage.setItem(this.$route.path + '-columnSet', JSON.stringify(this.showColumn));
            this.columnVisible = false;
          },
          //重置表单
          onRest(){
            this.$refs.formRef.resetFields();
          },
          CleanLog(){
            this.LogDialog = true;
          },
          submit() {
            this.$refs.formRef.validate((valid) => {
              if (valid) {
                  this.$http.put('/clean_log/',this.form)
                  .then(res => {
                    if (res.data.code == 200){
                      this.$message.success('清理成功');
                      this.getData(); //重新获取数据
                      this.LogDialog = false;  // 关闭窗口
                      this.onRest(); //重置表单
                    }
                  })
                  .catch((error)=>{

                  })
              } else {
                this.$message.error('格式错误！')
              }
            })
          },
        },
    }
</script>

<style scoped>
  .table-header {
    display: flex;
    margin-bottom: 18px;
    justify-content: space-between;
  }
</style>